<template>
    <div v-if="hasdata==0">
    </div>
    <div v-else-if="hasdata==1">
        <v-header :bg="info.type!=2?'tran':'light'" :hasgap="info.type==2">
            <div class="nav-tab2">
                <h3 v-show="info.type==2">资讯</h3>
            </div>
        </v-header>
        <ArticleDetl v-if="info.type==0" :info="info"></ArticleDetl>
        <VideoDetl v-if="info.type==2" :info="info"></VideoDetl>
        <PictureDetl v-if="info.type==1" :info="info"></PictureDetl>
        <v-delay :delay="300">
            <div class="compents_con" v-if="info.type!=1">
                <Warning-box v-if="!insq"></Warning-box>
                <Article-label :labelists="labels"></Article-label>
                <Zan-report v-if="!hideCmt" :diglist='digList' :artitype="articledtl.type" :digDetls="articledtl"></Zan-report>
                <div class="re_chang" v-if="relateArticles.length>0">
                    <span>相关推荐</span>
                    <span @click="changList"><span class="ico-chang" :class="{iconRun:isChang}"></span>换一批</span>
                </div>
                <Recomd-articles :artlist='relateArticles' :listType="listType"></Recomd-articles>
                <div v-if='honeyProdLists.length>0'>
                  <p style="margin-bottom:15px;margin-left:15px;">推荐商品</p>
                  <swiper :options="swiperHoneyProds" class="swiper-container swiperProds">
                    <swiper-slide v-for="item in honeyProdLists" :key='item.id' >
                      <ProductUnit :productItem='item' :productType="item.prodTp" ></ProductUnit>
                    </swiper-slide>
                  </swiper>
                </div>
                <!-- <Recomd-prods v-if='lazyLoaded.length>0' :recomdId='articleid' :isHideTitle="false"></Recomd-prods> -->
                <Comments v-if="comtLength>0&&!hideCmt" :comments='commentList' :lengComt="comtLength" :artitype="articledtl.type"></Comments>
                <Comment-fixed v-if='!hideCmt' :articleInfo='articledtl'></Comment-fixed>
            </div>
            <Backto-article v-if="!insq"></Backto-article>
        </v-delay>
    </div>
      <v-error v-else></v-error>
</template>
<script>
import { ArticleDetail, ArticleRelated, ArticleDetailSub } from '../../../common/api/article'
import { RecommendInArticle } from '../../../common/api/product'
import WarningBox from '../../templates/WarningBox'
import ArticleLabel from '../../templates/ArticleLabel'
import RecomdArticles from '../../templates/RecomdArticles'
import ZanReport from '../../templates/ZanReport'
import RecomdProds from '../../templates/RecomdProds'
import Comments from '../../templates/Comments'
import CommentFixed from '../../templates/CommentFixed'
import BacktoArticle from '../../templates/BacktoArticle'
import ArticleDetl from '../../templates/news/ArticleDetl'
import PictureDetl from '../../templates/news/PictureDetl'
import VideoDetl from '../../templates/news/VideoDetl'
import ProductUnit from '../../templates/ProductUnit'
import { DateDiffFormat } from '../../../common/util' // , endWithGif
import { mapGetters } from 'vuex'

const dom = window.document

export default {
  data() {
    return {
      // hideCmt: window.INSQ,
      hasdata: 0,
      articleid: '',
      articledtl: {},
      relateArticles: [],
      labels: [],
      comtLength: '',
      digList: [],
      commentList: [],
      listType: 0,
      isChang: false,
      timeRun: {},
      timeTwo: {},
      lazyLoaded: false,
      honeyProdLists: [],
      swiperHoneyProds: {
        slidesPerView: 2.5,
        freeMode: true,
        // slideToClickedSlide: true,
        lazyLoading: true,
        spaceBetween: 10
      }
    }
  },
  // beforeCreate() {
  //   const head = dom.querySelector('head')
  //   let js = dom.querySelector('#zxJs')
  //   if (!js) {
  //     js = dom.createElement('script')
  //     js.id = 'zxJs'
  //     js.src = 'https://files.eyee.com/EYEE/js/zx.js'
  //     head.appendChild(js)
  //   }
  //   let css = dom.querySelector('#zxCss')
  //   if (!css) {
  //     css = dom.createElement('link')
  //     css.id = 'zxCss'
  //     css.setAttribute('rel', 'stylesheet')
  //     css.setAttribute('href', 'https://files.eyee.com/EYEE/js/zx.css')
  //     head.appendChild(css)
  //   }
  // },
  mounted() {
    this.fetchData()
    // this.getInterAction()
    window.addEventListener('scroll', this.lazyLoad)
    this.reccommondProdect()
  },
  components: {
    WarningBox,
    ArticleLabel,
    RecomdArticles,
    RecomdProds,
    ZanReport,
    Comments,
    CommentFixed,
    BacktoArticle,
    ArticleDetl,
    PictureDetl,
    VideoDetl,
    ProductUnit
  },
  computed: {
    ...mapGetters({ insq: 'insq' }),
    info() {
      let info = this.articledtl
      // console.log('article detail',this.articledtl)
      if (info && info.id) info.publishtime = DateDiffFormat(info.publishtime)
      if (info.hasOwnProperty('content')) info.content = info.content.replace(/(eyee-src)/gi, 'src')
      return info
    },
    hideCmt() {
      return this.insq
    }
  },
  methods: {
    reccommondProdect: function () {
      var _ = this
      RecommendInArticle({ articleid: _.articleid }).then(function (res) {
        if (res) {
          _.honeyProdLists = res
        }
        console.log()
      })
    },
    getDetls: function () {
      var _ = this
      _.contentH = 0
      _.lazyLoaded = false
      window.scrollTo(0, 0)
      ArticleDetail({ articleid: _.articleid })
        .then(function (res) {
          console.log('详情', res)
          if (res && res.article) {
            let art = res.article
            _.hasdata = 1
            if (art.dealdata && art.type == 2) {
              art.videowords = eval('(' + art.dealdata + ')')
              art.videosources = eval('(' + art.dealdata + ')')[0].dataurl
            }
            if (art.type != 1) {
              _.listType = 1
            }
            if (art.type == 1 && art.dealdata) {
              art.pictureLists = JSON.parse(art.dealdata)
            }
            _.articledtl = art
            _.initShare({ type: 0, info: { title: art.title, img: art.coverurl }})
          } else _.hasdata = 2
        })
        .catch(e => {
          console.error('资讯详情加载失败', e)
          _.hasdata = 2
          _.toast('网络繁忙！')
        })
    },
    getRelate: function () {
      var _ = this
      ArticleRelated({ articleid: _.articleid })
        .then(function (res) {
          if (res) {
            console.log('推荐', res)
            _.relateArticles = res
          } else {
            console.log('没有推荐')
          }
          _.isChang = false
        })
        .catch(function (err) {
          console.log(err)
          _.isChang = false
          //    _.toast('获取推荐失败')
        })
    },
    getInterAction: function () {
      if (this.insq) return
      var _ = this
      ArticleDetailSub({ articleid: _.articleid })
        .then(function (res) {
          if (res) {
            console.log('相关推荐', res)
            if (res.labels && res.labels.length > 0) {
              _.labels = res.labels
            }
            if (res.comment && res.comment.list.length > 0) {
              _.comtLength = res.comment.list.length
              _.commentList = res.comment.list
            } else {
              _.comtLength = 0
            }
            if (res.digavatars) {
              _.digList = res.digavatars.reverse()
            }
          } else {
            console.log('没有评论')
          }
        })
        .catch(function (err) {
          console.log(err)
          // _.toast('获取评论失败')
        })
    },
    fetchData: function () {
      var _ = this
      _.articleid = _.$route.params.id
      _.getDetls()
      // 定时器
      // this.timeRun = setTimeout(() => {
      //   _.getRelate()
      // }, 4000)
      // if (!this.insq) {
      //   this.timeTwo = setTimeout(() => {
      //     _.getInterAction()
      //   }, 2000)
      // }
    },
    changList() {
      this.isChang = true
      this.getRelate()
    },
    lazyReq: function () {
      let _ = this
      _.changList()
      if (!this.insq) _.getInterAction()
    },
    lazyLoad() {
      let _ = this
      if (!_.lazyLoaded) {
        let cont = dom.querySelector('.detl_cont') || dom.querySelector('.infos_detl') || {}
        let H = cont.clientHeight || 9999
        let Y = window.scrollY
        let winH = window.innerHeight
        //  _.lazyLoaded = true
        //   _.lazyReq()
        // console.log('lazyLoad',  Y, H - winH - 180)
        if (Y > H - winH - 180) {
          console.log(29999)
          _.lazyLoaded = true
          _.lazyReq()
        }
      }
    }
  },
  beforeDestroy() {
    clearTimeout(this.timeRun)
    clearTimeout(this.timeTwo)
  },
  watch: {
    '$route.params.id': function (val, old) {
      // console.log('watch article id', val, old, this.$route.name)
      if (this.$route.name === 'article-detail' && val && val !== old) this.fetchData()
    }
    // '$route': 'fetchData'
  }
}
</script>
